// pages/mch/order/restore.js
const App = getApp()
import Qiniu from '../../../utils/qiniu'
import Kits from '../../../utils/kits'
import Util from '../../../utils/util'

Page({
  data: {
    init: false,
    debug: App.Global.Debug,
    order: {},
    mile: '',
    thing: '',
    photo: [],
    video: [],
    detail: [],

    amount: '',
    type: '1',
    memo: '',

    qrpay: false,
    qr: '',
    pamt: '',
    pcnl: '',
    pid: '',

    oilOpts: [{
      id: 1,
      name: '1 / 8'
    }, {
      id: 2,
      name: '2 / 8'
    }, {
      id: 3,
      name: '3 / 8'
    }, {
      id: 4,
      name: '4 / 8'
    }, {
      id: 5,
      name: '5 / 8'
    }, {
      id: 6,
      name: '6 / 8'
    }, {
      id: 7,
      name: '7 / 8'
    }, {
      id: 8,
      name: '8 / 8'
    }],
    oilIndex: 1,

    timer: undefined,

    forfeit_from_deposit: '',
    forfeit_from_deposit_type: 1,
    forfeit_from_deposit_memo: '',
    location: '',
    violation_time: '',
    add: false,
    forfeits: [],
    start_time: '',
    showUserInfo: false,
    timeShow: false,
    minDate: '',
    maxDate: new Date().getTime(),
    unbill: {},
    unbills: [],
  },
  onLoad(options) {
    this.execLoad(options.oid)
    this.load(options.oid)
  },
  load(id) {
    App.doPost({
      uri: '/app/merchant/violation/list',
      body: {
        order_id: Number(id)
      },
      fnSucc: resp => {
        this.setData({
          forfeits: resp.data.items
        })
      }
    })
  },
  addData() {
    this.setData({
      add: !this.data.add
    })
  },
  saveViolation() {
    if (this.data.Points % 3 !== 0 && this.data.Points != 1) {
      Util.Notify.warn(`请填写正确的违章扣分`)
      return
    }

    if (this.data.reason == '') {
      Util.Notify.warn(`请填写违章备注`)
      return
    }

    if (this.data.location == '') {
      Util.Notify.warn(`请填写违章地点`)
      return
    }

    if (this.data.violation_time == '') {
      Util.Notify.warn(`请选择违章时间`)
      return
    }
    const data = {
      order_id: Number(this.data.order.id),
      car_id: Number(this.data.order.car.id),
      reason: this.data.forfeit_from_deposit_memo,
      Points: this.data.Points * 1,
      forfeit: this.data.forfeit * 100,
      forfeit_from_deposit: this.data.forfeitFromDeposit * 100,
      violation_time: this.data.violation_time,
      location: this.data.location
    }
    
    App.doPost({
      uri: '/app/merchant/violation/save',
      body: data,
      fnSucc: resp => {
        this.addData()
        this.load(this.data.order.id)
      }
    })
  },
  onUnload() {
    if (this.data.timer) {
      clearTimeout(this.data.timer)
    }
  },
  execLoad(oid) {
    App.doPost({
      uri: '/app/merchant/order/detail',
      body: {
        id: oid
      },
      fnSucc: resp => {
        resp.data.deposit.totalStr = Kits.fmtMoneyString(resp.data.deposit.total)
        resp.data.rent.totalStr = Kits.fmtMoneyString(resp.data.rent.total)
        resp.data.rent.paidStr = Kits.fmtMoneyString(resp.data.rent.paid)
        this.data.unbill = {}
        const unbills = []
        resp.data.bills.forEach(bill => {
          if(bill.createTime){
            bill.createTime = this.formatCurrentYearTime(bill.createTime)
          }
          if(bill.finishTime){
            if(bill.finishTime === '0001-01-01T00:00:00Z'){
              bill.finishTime = ''
            }else{
              bill.finishTime = this.formatCurrentYearTime(bill.finishTime)
            }
          }
          if(bill.name === '违章罚款代缴'){
            bill.isHideMSBtn = true
          }
          if(bill.paymentChannel){
            bill.payType = this.getPayType(bill.paymentChannel)
          }
          if(bill.begin){
            bill.begin = this.formatCurrentYearTime(bill.begin)
          }
          if(bill.close){
            bill.close = this.formatCurrentYearTime(bill.close)
          }
          if(!bill.paid){
            unbills.push(bill)
          }
          if (!bill.paid && !this.data.unbill.id) {
            this.setData({
              unbill: bill
            })
          } else {
            this.setData({
              unbill: {}
            })
          }
        })
        this.setData({
          unbills: [...unbills]
        })
        console.log('unbills', this.data.unbills)
        let sources = []
        if(Array.isArray(resp.data.delivery.photo)){
          resp.data.delivery.photo.forEach(p => {
            sources[sources.length] = {
              url: p,
              type: 'image'
            }
          })
        }
        if(Array.isArray(resp.data.delivery.detail)){
          resp.data.delivery.detail.forEach(p => {
            sources[sources.length] = {
              url: p,
              type: 'image'
            }
          })
        }
        if(Array.isArray(resp.data.delivery.video)){
          resp.data.delivery.video.forEach(p => {
            sources[sources.length] = {
              url: p,
              type: 'video'
            }
          })
        }
        resp.data.delivery.sources = sources

        let sourcesrestore = []
        if(Array.isArray(resp.data.restore.photo)){
          resp.data.restore.photo.forEach(p => {
            sourcesrestore[sourcesrestore.length] = {
              url: p,
              type: 'image'
            }
          })
        }
        if(Array.isArray(resp.data.restore.detail)){
          resp.data.restore.detail.forEach(p => {
            sourcesrestore[sourcesrestore.length] = {
              url: p,
              type: 'image'
            }
          })
        }
        if(Array.isArray(resp.data.restore.video)){
          resp.data.restore.video.forEach(p => {
            sourcesrestore[sourcesrestore.length] = {
              url: p,
              type: 'video'
            }
          })
        }
        resp.data.restore.sources = sourcesrestore
        const newBills = []
        if(resp.data.bills && Array.isArray(resp.data.bills)){
          resp.data.bills.forEach(bill=>{
            const findNewBillIndex = newBills.findIndex(nBill=>nBill.type === bill.type)
            if(findNewBillIndex > -1){
              const billItem = newBills[findNewBillIndex]
              if(billItem.begin && billItem.close){
                billItem.begin = billItem.begin > bill.begin ? bill.begin : billItem.begin
                billItem.close = billItem.close < bill.close ? bill.close : billItem.close
              }
              newBills[findNewBillIndex].amount = Number(billItem.amount) + Number(bill.amount)
              if(bill.originalAmount){
                newBills[findNewBillIndex].originalAmounttotal = Number(newBills[findNewBillIndex].originalAmounttotal || 0) + Number(bill.originalAmount / 100)
              }else{
                newBills[findNewBillIndex].originalAmounttotal = Number(newBills[findNewBillIndex].originalAmounttotal) + Number(bill.amount)
              }
            }else{
              newBills.push({
                ...bill,
                originalAmounttotal: 
                bill.originalAmount ? Number(bill.originalAmount / 100) : Number(bill.amount)
              })
            }
          })
        }
        newBills.forEach(item=>{
          if(item.begin && item.close){
            // 计算出天数
            const begin = new Date(item.begin)
            const close = new Date(item.close)
            const days = (close.getTime() - begin.getTime()) / (1000 * 60 * 60 * 24)
            item.days = Math.ceil(days)
            // 平均每天的金额
            item.avgPrice = (item.amount / item.days).toFixed(2)
          }
        })
        resp.data.newBills = newBills
        console.log('newBills', resp.data.bills,newBills)

        const formatTimes = ()=>{
          // 时间轴
          const timelines = []
          if(resp.data.times){
            if(resp.data.times.paid){
              timelines.push({
                time: resp.data.times.paid,
                timeStr: this.formatCurrentYearTimeSencord(resp.data.times.paid),
                title: '付款时间'
              })
            }
            if(resp.data.times.delivery){
              timelines.push({
                time: resp.data.times.delivery,
                timeStr: this.formatCurrentYearTimeSencord(resp.data.times.delivery),
                title: '交车时间'
              })
            }
          }
          if(resp.data.deposit.part){
            timelines.push({
              time: resp.data.deposit.part,
              timeStr: this.formatCurrentYearTimeSencord(resp.data.deposit.part),
              title: '车辆押金退款'
            })
          }
          if(resp.data.deposit.full){
            timelines.push({
              time: resp.data.deposit.full,
              timeStr: this.formatCurrentYearTimeSencord(resp.data.deposit.full),
              title: '违章押金退款'
            })
          }
          if(resp.data.times.create){
            resp.data.times.createStr = this.formatCurrentYearTimeSencord(resp.data.times.create)
          }
          if(resp.data.delivery.time){
            resp.data.delivery.timeStr = this.formatCurrentYearTimeSencord(resp.data.delivery.time)
          }
          if(resp.data.restore.time){
            resp.data.restore.timeStr = this.formatCurrentYearTimeSencord(resp.data.restore.time)
          }
          // 按时间排序
          timelines.sort((a,b)=>{
            return new Date(a.time).getTime() - new Date(b.time).getTime() > 0 ? -1 : 1
          })
          resp.data.timelines = timelines

          resp.data.beginStr = this.formatCurrentYearTime(resp.data.begin)
          resp.data.closeStr = this.formatCurrentYearTime(resp.data.close)
        }
        formatTimes()
        this.setData({
          init: true,
          order: resp.data,
          minDate: new Date(resp.data.begin + ':00').getTime(),
          maxDate: new Date(resp.data.close + ':00').getTime()
        })
        this.data.order.newBills.forEach(item=>{
          if(typeof item.amount == 'string'){
            item.amount=parseInt(item.amount)
          }
        })
        this.setData({
          'order.newBills':this.data.order.newBills
        })
        this.load(options.oid)
      }
    })
  },
 
  formatCurrentYearTimeSencord (time) {
    const date = new Date(time)
    const now = new Date()
    if (date.getFullYear() === now.getFullYear()) {
      return date.format('MM-dd HH:mm:ss')
    } else {
      return date.format('yyyy-MM-dd HH:mm:ss')
    }
  },
  formatTimestamp(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  formatTimestampMitute(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },
  onInput(e) {
    console.log(e.detail,"时间");
    const date = this.formatTimestamp(e.detail)
    this.setData({
      violation_time: date,
      timeShow: false
    })
    console.log(this.data.violation_time,"dfgfehte")
  },
  onCloseTime() {
    this.setData({
      timeShow: !this.data.timeShow
    })
    console.log(this.data.minDate,this.data.maxDate,"最大最小时间")
  },
  doTypeChange(e) {
    this.setData({
      type: parseInt(e.currentTarget.dataset.type)
    })
  },
  doTypeChange1(e) {
    this.setData({
      type: parseInt(e.currentTarget.dataset.type)
    })
  },

  doChooseItem(e) {
    let type = e.currentTarget.dataset.type
    wx.chooseMedia({
      count: 1,
      mediaType: [type == 'video' ? 'video' : 'image'],
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      maxDuration: 60,
      camera: 'back',
      success: (res) => {
        this.execUpload(res.tempFiles[0].tempFilePath, type)
      }
    })
  },
  execUpload(path, type) {
    App.doPost({
      uri: '/comm/tool/file/qiniu/info',
      body: {
        type: type == 'video' ? 'Video' : 'Image'
      },
      fnSucc: resp => {
        let key = resp.data.path + resp.data.fileid + '.' + path.split('.').pop()?.toLowerCase()
        Qiniu.upload(path, (res) => {
          if (type == 'photo') {
            let srcs = this.data.photo
            srcs[srcs.length] = res.imageURL
            this.setData({
              photo: srcs
            })
          }
          if (type == 'video') {
            let srcs = this.data.video
            srcs[srcs.length] = res.imageURL
            this.setData({
              video: srcs
            })
          }
          if (type == 'detail') {
            let srcs = this.data.detail
            srcs[srcs.length] = res.imageURL
            this.setData({
              detail: srcs
            })
          }
        }, (err) => {
          console.log(err)
        }, {
          region: 'NCN',
          key: key,
          uptoken: resp.data.token,
          uptokenFunc: null,
          uptokenURL: null,
          domain: resp.data.domain,
          shouldUseQiniuFileName: false,
        }, () => {

        }, () => {

        })
      },
      fnFail: resp => {
        App.doAlert('出错啦', `上传失败，[${resp.stat.err}] ${resp.stat.msg}`)
      }
    })
  },
  doPreviewItem(e) {
    let type = e.currentTarget.dataset.type
    let sources = []

    this.data[type].forEach(p => {
      sources[sources.length] = {
        url: p,
        type: type == 'video' ? 'video' : 'image'
      }
    })

    let current = this.data[type].findIndex(p => p == e.currentTarget.dataset.url)
    console.log(sources, current)
    wx.previewMedia({
      sources: sources,
      current: current
    })
  },
  doPreviewDeliveryItem(e) {
    let type = e.currentTarget.dataset.type
    let sources = []

    this.data.order.delivery[type].forEach(p => {
      sources[sources.length] = {
        url: p,
        type: type == 'video' ? 'video' : 'image'
      }
    })

    let current = this.data.order.delivery[type].findIndex(p => p == e.currentTarget.dataset.url)
    console.log(sources, current)
    wx.previewMedia({
      sources: sources,
      current: current
    })
  },
  doDeleteItem(e) {
    if (e.currentTarget.dataset.type == 'photo') {
      this.data.photo.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        photo: this.data.photo
      })
    }
    if (e.currentTarget.dataset.type == 'video') {
      this.data.video.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        video: this.data.video
      })
    }
    if (e.currentTarget.dataset.type == 'detail') {
      this.data.detail.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        detail: this.data.detail
      })
    }

  },
  doOilChange(e) {
    this.setData({
      oilIndex: e.detail.value
    })
  },
  doPayment(e) {
    if (this.data.loading) {
      return
    }
    this.setData({
      loading: true
    })
    let type = e.currentTarget.dataset.type
    this.setData({
      qr: ''
    })
    App.doPost({
      uri: '/app/merchant/order/pay/qr',
      body: {
        type: 'Supp',
        data: this.data.order.id,
        pcnl: parseInt(type),
        parg: JSON.stringify({
          appid: App.Global.AppId,
          puser: App.Global.OpenId,
        })
      },
      fnSucc: (resp) => {
        let url = type == '20' ? resp.data.wxqr.url : resp.data.aliqr.url
        this.setData({
          pid: resp.data.id,
          qr: url,
          pamt: Kits.fmtMoneyString(resp.data.amount),
          pcnl: type == '20' ? '微信' : '支付宝'
        })
        this.execCheckPay()
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false
        })
      }
    })

  },
  execCheckPay() {
    App.doPost({
      uri: '/app/base/payment/state',
      body: {
        id: this.data.pid,
      },
      fnSucc: resp => {
        if (resp.data.state == 1) {
          if (this.data.timer) {
            clearTimeout(this.data.timer)
          }
          this.data.timer = setTimeout(() => {
            this.execCheckPay()
          }, 2000)
          return
        }
        Util.Toast.clear()
        if (resp.data.state == 2) {
          Util.Toast.succ('用户已支付')
          this.setData({
            qrpay: false
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000)
        }
      },
    })
  },
  execTestPay() {
    if (!this.data.debug) {
      return
    }
    if (this.data.loading) {
      return
    }
    this.setData({
      loading: true
    })

    App.doPost({
      uri: '/dev/op/payment/finish',
      body: {
        pid: this.data.pid,
      },
      fnSucc: resp => {
        console.log(resp.data)
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false
        })
      }
    })
  },
  execSave() {


    if (!this.data.mile) {
      Util.Notify.warn(`请填写行驶里程`)
      return
    }
    if (parseInt(this.data.mile) < this.data.order.delivery.mile) {
      Util.Notify.warn(`不可小于交车时里程`)
      return
    }
    if (this.data.photo.length == 0 && this.data.video.length == 0) {
      Util.Notify.warn(`请上传验车图片或视频`)
      return
    }
    if (parseInt(this.data.amount) * 100 > 0 && this.data.memo == '') {
      Util.Notify.warn(`请填写补收说明`)
      return
    }

    this.setData({
      loading: true
    })
    App.doPost({
      uri: '/app/merchant/order/restore',
      body: {
        id: this.data.order.id,
        info: {
          mile: parseInt(this.data.mile),
          fuel: parseInt(this.data.oilIndex) + 1,
          thing: this.data.thing
        },
        photo: this.data.photo,
        video: this.data.video,
        detail: this.data.detail,
        amount: parseInt(this.data.amount) * 100,
        memo: this.data.memo
      },
      fnSucc: () => {
        wx.pub("ReloadOrderList", {})
        Util.Toast.succ(`收车成功`)
        if (parseInt(this.data.amount) > 0 && this.data.type == 1) {
          this.setData({
            qrpay: true
          })

        } else {
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000);
        }
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  showUserInfoMet(){
    this.setData({
      showUserInfo: !this.data.showUserInfo
    })
  },
  doChangeOilSlider(e){
    console.log(e.detail.value)
    this.setData({
      oilIndex: e.detail.value
    })
  },
  formatCurrentYearTime (time) {
    const date = new Date(time)
    const now = new Date()
    if (date.getFullYear() === now.getFullYear()) {
      return date.format('MM-dd HH:mm')
    } else {
      return date.format('yyyy-MM-dd HH:mm')
    }
  },
})